package org.browntooth.app.communicator;

import java.util.UUID;

import org.browntooth.app.bluetooth.Bluetooth;
import org.browntooth.app.bluetooth.BluetoothDeviceConnection;
import org.browntooth.app.bluetooth.BluetoothDisabledException;
import org.browntooth.app.bluetooth.BluetoothEventListener;

import android.bluetooth.BluetoothDevice;
import android.util.Log;

public class BrowntoothCommunicator {
	public static final UUID BROWNTOOTH_SERVICE_UUID = UUID
			.fromString("55ff3915-f55a-4142-bf27-904764df8220");
	public static final String BROWNTOOTH_SERVICE_NAME = "Browntooth";

	private final Bluetooth bluetooth;
	private BrowntoothCommunicator listener;

	public BrowntoothCommunicator(Bluetooth bluetooth) {
		this.bluetooth = bluetooth;

		this.bluetooth.setListener(new BluetoothEventListener() {
			public void connectedToDivece(BluetoothDeviceConnection connection) {
				handleConnection(connection);
			}

			public void remoteDeviceConnectionFailed(UUID serviceUuid,
					Exception exception) {
				// TODO Auto-generated method stub
			}

			public void deviceDiscovered(BluetoothDevice device) {
				// Not interesting
			}

			public void connectionToDiveceFailed(BluetoothDevice device,
					UUID serviceUuid, Exception exception) {
				// Not interesting
			}
		});
	}

	public void start() throws BluetoothDisabledException {
		bluetooth.validateEnabled();
		bluetooth.listen(BROWNTOOTH_SERVICE_UUID, BROWNTOOTH_SERVICE_NAME);
	}

	public void setListener(BrowntoothCommunicator listener) {
		this.listener = listener;
	}
	
	public void handleConnection(BluetoothDeviceConnection connection) {
		try {
			Log.d("Browntooth", "CONNECTED!");
			
			BrowntoothCommunication com = new BrowntoothCommunication(connection);
			com.start();
		} catch (Exception e) {
			// TODO Auto-generated catch block
		}
		
	}
}
